{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cf472e46-ac20-41d9-a88d-643be1795ec3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "\n",
    "from autogen_agentchat.agents import AssistantAgent\n",
    "from autogen_agentchat.base import TaskResult\n",
    "from autogen_agentchat.conditions import ExternalTermination, TextMentionTermination\n",
    "from autogen_agentchat.teams import RoundRobinGroupChat\n",
    "from autogen_agentchat.ui import Console\n",
    "from autogen_core import CancellationToken\n",
    "from autogen_ext.models.ollama import OllamaChatCompletionClient\n",
    "\n",
    "# Assuming your Ollama server is running locally on port 11434.\n",
    "model_client = OllamaChatCompletionClient(\n",
    "        model=\"hhao/qwen2.5-coder-tools:latest\",\n",
    "        #model=\"qwen2.5-coder:latest\",\n",
    "        #model=\"GandalfBaum/deepseek_r1-claude3.7:latest\",\n",
    "        #model = \"GandalfBaum/llama3.2-claude3.7:latest\",\n",
    "        host=\"http://192.168.99.142:11434\", \n",
    "        model_info={\n",
    "        \"vision\": False,\n",
    "        \"function_calling\": True,\n",
    "        \"json_output\": True,\n",
    "        \"family\": \"unknow\",\n",
    "        \"structed_output\":True,\n",
    "        },\n",
    "    )\n",
    "\n",
    "# Create the primary agent.\n",
    "primary_agent = AssistantAgent(\n",
    "    \"primary\",\n",
    "    model_client=model_client,\n",
    "    system_message=\"You are a helpful AI assistant.\",\n",
    ")\n",
    "\n",
    "# Create the critic agent.\n",
    "critic_agent = AssistantAgent(\n",
    "    \"critic\",\n",
    "    model_client=model_client,\n",
    "    system_message=\"Provide constructive feedback. Respond with 'APPROVE' to when your feedbacks are addressed.\",\n",
    ")\n",
    "\n",
    "# Define a termination condition that stops the task if the critic approves.\n",
    "text_termination = TextMentionTermination(\"APPROVE\")\n",
    "\n",
    "# Create a team with the primary and critic agents.\n",
    "team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=text_termination)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9fc093d3-d5e1-4351-a9bd-03fd17a07292",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "TaskResult(messages=[TextMessage(source='user', models_usage=None, content='Write a short poem about the fall season.', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=29, completion_tokens=85), content=\"Leaves whisper to the ground,\\nCrisp air dances through the trees,\\nNature's palette turns to gold,\\nAs autumn's gentle breeze.\\n\\nSunset paints the sky in hues,\\nOrange, red, and amber glow,\\nEach leaf a story untold,\\nOf summer's warmth and show.\\n\\nThe world slows down its pace,\\nAs nature prepares for sleep,\\nA time of rest and grace,\\nBefore the cycle repeats.\", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=125, completion_tokens=44), content='Your poem captures the essence of fall beautifully! The imagery is vivid, and the emotions conveyed are authentic. It effectively conveys the transition from summer to autumn, highlighting the changing colors and the serene atmosphere. APPROVE', type='TextMessage')], stop_reason=\"Text 'APPROVE' mentioned\")\n"
     ]
    }
   ],
   "source": [
    "# Use `asyncio.run(...)` when running in a script.\n",
    "result = await team.run(task=\"Write a short poem about the fall season.\")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "226d36b1-e599-4dd7-9d76-33ec3ec0e63c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------- user ----------\n",
      "Write a short poem about the fall season.\n",
      "---------- primary ----------\n",
      "Leaves whisper to the ground,\n",
      "Crisp air dances through the trees,\n",
      "Nature's palette turns to gold,\n",
      "As autumn's gentle breeze blows.\n",
      "\n",
      "Sunset paints the sky in hues,\n",
      "Orange, red, and amber glow,\n",
      "Each leaf a story untold,\n",
      "In the fading light of day.\n",
      "\n",
      "The world slows down its pace,\n",
      "As nature prepares for sleep,\n",
      "A time of rest and grace,\n",
      "Before the cycle begins anew.\n",
      "[Prompt tokens: 29, Completion tokens: 87]\n",
      "---------- critic ----------\n",
      "APPROVE\n",
      "[Prompt tokens: 127, Completion tokens: 4]\n",
      "---------- Summary ----------\n",
      "Number of messages: 3\n",
      "Finish reason: Text 'APPROVE' mentioned\n",
      "Total prompt tokens: 156\n",
      "Total completion tokens: 91\n",
      "Duration: 1.72 seconds\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "TaskResult(messages=[TextMessage(source='user', models_usage=None, content='Write a short poem about the fall season.', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=29, completion_tokens=87), content=\"Leaves whisper to the ground,\\nCrisp air dances through the trees,\\nNature's palette turns to gold,\\nAs autumn's gentle breeze blows.\\n\\nSunset paints the sky in hues,\\nOrange, red, and amber glow,\\nEach leaf a story untold,\\nIn the fading light of day.\\n\\nThe world slows down its pace,\\nAs nature prepares for sleep,\\nA time of rest and grace,\\nBefore the cycle begins anew.\", type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=127, completion_tokens=4), content='APPROVE', type='TextMessage')], stop_reason=\"Text 'APPROVE' mentioned\")"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "await team.reset()  # Reset the team for a new task.\n",
    "await Console(team.run_stream(task=\"Write a short poem about the fall season.\"))  # Stream the messages to the console."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c77229c7-3c7e-4e65-86e3-f4661d24d5b1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------- user ----------\n",
      "将这首诗用中文唐诗风格写一遍。\n",
      "---------- primary ----------\n",
      "秋风扫落叶，飘零似梦魂。\n",
      "金黄满地铺，红艳映朝昏。\n",
      "\n",
      "晚霞映天际，色彩斑斓新。\n",
      "夕阳西下后，夜幕悄然临。\n",
      "\n",
      "万物皆安详，静待春回转。\n",
      "秋之韵悠长，岁月轮回显。\n",
      "[Prompt tokens: 140, Completion tokens: 65]\n",
      "---------- critic ----------\n",
      "APPROVE\n",
      "[Prompt tokens: 215, Completion tokens: 4]\n",
      "---------- Summary ----------\n",
      "Number of messages: 3\n",
      "Finish reason: Text 'APPROVE' mentioned\n",
      "Total prompt tokens: 355\n",
      "Total completion tokens: 69\n",
      "Duration: 2.28 seconds\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "TaskResult(messages=[TextMessage(source='user', models_usage=None, content='将这首诗用中文唐诗风格写一遍。', type='TextMessage'), TextMessage(source='primary', models_usage=RequestUsage(prompt_tokens=140, completion_tokens=65), content='秋风扫落叶，飘零似梦魂。\\n金黄满地铺，红艳映朝昏。\\n\\n晚霞映天际，色彩斑斓新。\\n夕阳西下后，夜幕悄然临。\\n\\n万物皆安详，静待春回转。\\n秋之韵悠长，岁月轮回显。', type='TextMessage'), TextMessage(source='critic', models_usage=RequestUsage(prompt_tokens=215, completion_tokens=4), content='APPROVE', type='TextMessage')], stop_reason=\"Text 'APPROVE' mentioned\")"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# The new task is to translate the same poem to Chinese Tang-style poetry.\n",
    "await Console(team.run_stream(task=\"将这首诗用中文唐诗风格写一遍。\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3c7f89d-cdbb-4623-88eb-1ac616431d47",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
